<!--
 * @LastEditTime : 2022-10-31 16:04:47
 * @FilePath     : /pyy/src/views/physics/add/index.vue
 * @Description  : 物理分析 > 新增物理分析
-->
<template>
  <div id="physics-add">
    <van-nav-bar title="物理分析检测" left-arrow @click-left="goBack" />

    <div class="contaniner">
      <van-form
        label-width="180px"
        input-align="right"
        error-message-align="right"
        scroll-to-error
        validate-trigger="onChange"
        @submit="handleSubmit"
      >
        <div class="form-group">
          <van-field
            name="consignorW"
            class="mandatory"
            label="委托人"
            :rules="[{ required: true, message: '不能为空' }]"
            placeholder="请填写"
            autocomplete="off"
            v-model="form.consignorW"
          />
          <van-field
            name="clientName"
            class="mandatory"
            label="委托方客户名称"
            :rules="[{ required: true, message: '不能为空' }]"
            placeholder="请填写"
            autocomplete="off"
            v-model="form.clientName"
          />
          <van-field
            name="principalPhone"
            label="委托人电话"
            placeholder="请填写"
            class="mandatory"
            autocomplete="off"
            :rules="[
              {
                validator: (val) => {
                  if (!val) return true;
                  return /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(
                    val
                  );
                },

                message: '请输入正确的电话号码',
              },
              { required: true, message: '请输入电话号码' },
            ]"
            v-model="form.principalPhone"
          />
          <van-field
            autosize
            rows="1"
            type="textarea"
            name="principalAdd"
            class="mandatory"
            label="委托人地址"
            :rules="[{ required: true, message: '不能为空' }]"
            placeholder="请填写"
            autocomplete="off"
            v-model="form.principalAdd"
          />
          <popup-select
            name="contractReview"
            label="简化合同评审"
            placeholder="请选择"
            :options="relationData.whetherOptions"
            :default-props="{
              label: 'name',
              value: 'id',
            }"
            v-model="form.contractReview"
          />
          <!-- <van-field
            name="contractCode"
            label="合同编码"
            placeholder="请填写"
            autocomplete="off"
            :readonly="simplifyTheContractReview"
            v-model="form.contractCode"
          /> -->
          <popup-select
            name="organization"
            class="mandatory2"
            label="检验机构"
            placeholder="请选择"
            :rules="[{ required: true, message: '不能为空' }]"
            :options="relationData.organizationOptions"
            :default-props="{
              label: 'name',
              value: 'id',
            }"
            v-model="form.organization"
          />
          <popup-select
            name="toWay"
            label="样品送样方式"
            placeholder="请选择"
            :options="relationData.toWayOptions"
            :defaultSelect="defaultSelect"
            :default-props="{
              label: 'name',
              value: 'id',
            }"
            v-model="form.toWay"
          />
<!--          <van-field-->
<!--            readonly-->
<!--            name="analysisSum"-->
<!--            type="number"-->
<!--            label="分析检测金额"-->
<!--            placeholder="请输入数字"-->
<!--            autocomplete="off"-->
<!--            :value="analysisSum"-->
<!--          />-->
          <van-field name="require" label="是否同意检验要求">
            <template #input>
              <van-radio-group direction="horizontal" v-model="form.require">
                <van-row type="flex" justify="space-between">
                  <van-col
                    v-for="item in relationData.whetherOptions"
                    :key="item.id"
                  >
                    <radio-circle icon-size="16px" :name="item.id">
                      {{ item.name }}
                    </radio-circle>
                  </van-col>
                </van-row>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            autosize
            rows="1"
            type="textarea"
            name="means"
            label="手动输入方法"
            placeholder="请输入"
            autocomplete="off"
            :disabled="isRequire"
            v-model="form.means"
          />
          <uploader
            label="手动输入方法附件"
            placeholder="请上传附件"
            :disabled="isRequire"
            v-model="form.meansAttachment"
          />
          <van-field name="dispose" label="样品是否按实验室规定处理">
            <template #input>
              <van-radio-group direction="horizontal" v-model="form.dispose">
                <van-row type="flex" justify="space-between">
                  <van-col
                    v-for="item in relationData.whetherOptions"
                    :key="item.id"
                  >
                    <radio-circle icon-size="16px" :name="item.id">
                      {{ item.name }}
                    </radio-circle>
                  </van-col>
                </van-row>
              </van-radio-group>
            </template>
          </van-field>
          <van-field name="urgent" label="是否加急">
            <template #input>
              <van-radio-group direction="horizontal" v-model="form.urgent">
                <van-row type="flex" justify="space-between">
                  <van-col
                    v-for="item in relationData.whetherOptions"
                    :key="item.id"
                  >
                    <radio-circle icon-size="16px" :name="item.id">
                      {{ item.name }}
                    </radio-circle>
                  </van-col>
                </van-row>
              </van-radio-group>
            </template>
          </van-field>
          <calendar
            name="takeDate"
            label="计划客户取报告日期"
            placeholder="请选择日期"
            v-model="form.takeDate"
          />
          <van-field name="report" label="是否需要报告">
            <template #input>
              <van-radio-group direction="horizontal" v-model="form.report">
                <van-row type="flex" justify="space-between">
                  <van-col
                    v-for="item in relationData.whetherOptions"
                    :key="item.id"
                  >
                    <radio-circle icon-size="16px" :name="item.id">
                      {{ item.name }}
                    </radio-circle>
                  </van-col>
                </van-row>
              </van-radio-group>
            </template>
          </van-field>
          <!-- <van-uploader :after-read="afterRead" v-show="whetherYouNeedToReport" class="theTestReport">
            <van-field
            autosize
            rows="1"
            type="textarea"
            accept=".pdf"
            name="means"
            label="检测报告-盖章"
            v-model="form.theTestReport"      
          />
          </van-uploader> -->

          <!-- <van-uploader
            v-show="whetherYouNeedToReport"
            multiple
            v-model="form.theTestReport"
            ref="uploaderRef"
            :beforeRead="beforeRead"
            :after-read="afterRead"
          >
            <van-field
              autosize
              rows="1"
              type="textarea"
              name="theTestReport"
              readonly
              class="theTestReport"
              v-bind="$attrs"
              label="检测报告-盖章"
              @click="handleClick"
            >
            </van-field>
          </van-uploader> -->
        </div>
        <detailed
          v-for="(item, index) in form.child"
          :key="'detailed_' + index"
          :index="index"
          :show-delete="index < form.child.length - 1"
          :form.sync="item"
          :organization-id="form.organization"
          @delete="(i) => form.child.splice(i, 1)"
          @copy="
            (i) => form.child.push(JSON.parse(JSON.stringify(form.child[i])))
          "
        />
        <van-button
          block
          type="default"
          class="btn-add-detailed"
          icon="plus"
          native-type="button"
          @click="handleAddDetailed"
        >
          新增明细
        </van-button>
        <div class="btn-groups">
          <van-button
            class="btn-submit"
            round
            block
            type="info"
            native-type="submit"
          >
            提交
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import Uploader from "./components/uploader.vue";
import Detailed from "./components/detailed.vue";
import { Toast } from "vant";

import api from "@/http/api";

export default {
  name: "PhysicsAdd",
  components: {
    Uploader,
    Detailed,
  },
  data() {
    return {
      defaultSelect:{},
      relationData: {
        // 检验机构
        organizationOptions: [],
        // 样品送样方式
        toWayOptions: [],
        // 是否
        whetherOptions: [],
      },

      form: {
        consignorW: "",
        clientName: "",
        principalPhone: "",
        principalAdd: "",
        contractReview: "",
        contractCode: "",
        organization: "",
        toWay: "",
        analysisSum: null,
        require: "",
        means: "",
        meansAttachment: [],
        theTestReport: [], //附件
        testRport: [], //附件返回的值
        dispose: "",
        urgent: "",
        takeDate: "",
        report: "",
        theAttachment: null, //附件
        child: [],
      },
    };
  },
  computed: {
    // 是否同意检验要求
    isRequire() {
      const result = this.relationData.whetherOptions.find(
        (item) => item.id == this.form.require
      );
      return result ? result.name == "是" : false;
    },
    // 是否需要报告
    whetherYouNeedToReport() {
      const result = this.relationData.whetherOptions.find(
        (item) => item.id == this.form.report
      );
      return result ? result.name == "是" : false;
    },
    // 是否简化合同评审
    simplifyTheContractReview() {
      const result = this.relationData.whetherOptions.find(
        (item) => item.id == this.form.contractReview
      );
      return result ? result.name == "否" : false;
    },
    // 是否加急
    isUrgent() {
      const result = this.relationData.whetherOptions.find(
        (item) => item.id == this.form.urgent
      );
      return result ? result.name == "是" : false;
    },
    // 分析检测金额
    analysisSum() {
      /**
       * 是否加急
       * - 是: 费用 乘以2
       * - 否: 费用是多少，就是多少
       */
      return (this.form.analysisSum ?? 0) * (this.isUrgent ? 2 : 1) || null;
    },
  },
  watch: {
    "form.child": {
      handler(child) {
        // 分析检测金额: 明细表金额合集
        this.form.analysisSum = child.reduce((result, current) => {
          // const amount = [null, undefined, ""].includes(current.amount)
          const amount = [null, undefined, ""].includes(current.amount)
            ? 1
            : Number(current.amount);
        
          result += current.cost;
          return result;
        }, 0);

       
      },
      deep: true,
    },
  },
  created() {
    this.initRelationData();
  },
  mounted() {

  },
  methods: {
    handleAddCopy() {},
    handleDelete() {},
    // 返回布尔值
    beforeRead(file) {
      if (file.type != "application/pdf") {
        Toast("请上传 pdf 格式文件");
        return false;
      }
      return true;
    },
    /**
     * 输入框 点击事件
     */
    handleClick() {
      // 手动调用 组件上传 功能
      this.$refs.uploaderRef.chooseFile();
    },
    afterRead(file) {
      let formData = new FormData();
      formData.append("file", file.file);
      this.form.theAttachment = formData;
      api.file.upload(formData).then((res) => {
        const { code, data = [] } = res.data;
        if (code === 200) {
          this.form.testRport = res.data.data;
        }
      });
    },
    goBack() {
      this.$router.replace("/physics");
    },

    /**
     * 初始化 关联数据
     */
    initRelationData() {
      const toast = Toast.loading({
        duration: 0,
        forbidClick: true,
      });

      api.physics
        .getEnum()
        .then((res) => {
          const { code, data = {}, msg } = res.data || {};
          if (code !== 200) return Toast.fail(msg);
          let result = data["物理实验室选择"]
          let newArr=[]
          result.forEach((item)=>{
            if(item.code=="jinxiang" || item.code=="yanxiang" || item.code=="lixue"){
              newArr.push(item)
            }
          })
          this.relationData.organizationOptions = newArr;
          this.relationData.toWayOptions = data["样品送样方式"] || [];
          this.defaultSelect =this.relationData.toWayOptions[0]//默认选择第一个
          this.form.toWay = this.relationData.toWayOptions[0].id//默认选择第一个
          this.relationData.whetherOptions = data["是否"] || [];

          this.setDefaultData();
        })
        .finally(() => {
          toast.clear();
        });
    },

    /**
     * 设置 默认数据
     */
    setDefaultData() {
      // 默认选中 是
      const result = this.relationData.whetherOptions[0] || {};
      this.form.require = result.id;
      this.form.dispose = result.id;
      this.form.urgent = result.id;
      this.form.report = result.id;
    },

    /**
     * 点击 新增明细表
     */
    handleAddDetailed() {
      if (!this.form.organization) return Toast.fail("请选择检验机构");
      this.form.child.push({
        sampleName: "",
        sampleCode: "",
        sampleState: "",
        specification: "",
        amount: null,
        detectionBig: "",
        detectionSmall: "",
        cost: null,
        remark: "",
      });
    },
    // 点击复制
    handleAddCopy() {
      this.form.child.push({
        sampleName: "",
        sampleCode: "",
        sampleState: "",
        specification: "",
        amount: null,
        detectionBig: "",
        detectionSmall: "",
        cost: null,
        remark: "",
      });
    },

    /**
     * 点击 提交
     */
    async handleSubmit() {
      console.log("提交");
      const toast = Toast.loading({
        duration: 0,
        forbidClick: true,
      });

      const { meansAttachment = [] } = this.form || {};
      let uploadFileList = [];

      if (meansAttachment.length) {
        const formData = new FormData();
        meansAttachment.forEach((item) => {
          formData.append("file", item.file);
        });

        uploadFileList = await api.file
          .upload(formData)
          .then((res) => {
            const { code, data = [], msg } = res.data || {};
            if (code !== 200) {
              Toast.fail(msg || "文件上传失败");
              return [];
            }
            return data;
          })
          .catch(() => []);
      }
      if (meansAttachment.length != uploadFileList.length) {
        toast.clear();
        return;
      }
      if(this.getDate() === this.getCurrentMonthLastDay(new Date())){
        Toast.fail("月末最后四天内，不能提交");
      }else if(this.getDate() === this.getCurrentMonthLastDay2(new Date())){
        Toast.fail("月末最后四天内，不能提交");
      }else if(this.getDate() === this.getCurrentMonthLastDay3(new Date())){
        Toast.fail("月末最后四天内，不能提交");
      }else if(this.getDate() === this.getCurrentMonthLastDay4(new Date())){
        Toast.fail("月末最后四天内，不能提交");
      }else{
        api.physics
        .addProcess({
          ...this.form,
          analysisSum: this.analysisSum,
          meansAttachment: uploadFileList,
        })
        .then((res) => {
          const { code, msg } = res.data || {};
          if (code !== 200) return Toast.fail(msg);
          Toast.success("发起成功");
          setTimeout(this.goBack, 1000);
        })
        .finally(() => {
          setTimeout(toast.clear, 500);
        });
      }

    },
    getDate(){
    var myDate = new Date();	//创建Date对象
    var Y = myDate.getFullYear();   //获取当前完整年份
    var M = myDate.getMonth() + 1;  //获取当前月份
    var D = myDate.getDate();   //获取当前日1-31
    var H = myDate.getHours();  //获取当前小时
    var i = myDate.getMinutes();    //获取当前分钟
    var s = myDate.getSeconds();    //获取当前秒数
    // 月份不足10补0
    if(M < 10){
        M = '0' + M;
    }
    // 日不足10补0
    if(D < 10){
        D = '0' + D;
    }
    // 小时不足10补0
    if(H < 10){
        H = '0' + H;
    }
    // 分钟不足10补0
    if(i < 10){
        i = '0' + i;
    }
    // 秒数不足10补0
    if(s < 10){
        s = '0' +s;
    }
    // 拼接日期分隔符根据自己的需要来修改
    var nowDate = Y+'-'+M+'-'+ D
    return nowDate

    },
    // 获取当月最后一天
    getCurrentMonthLastDay() {
      let date = new Date();
      let currentMonth = date.getMonth();
      let nextMonth = ++currentMonth;
      let nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
      let oneDay = 1000 * 60 * 60 * 24;
      let lastTime = new Date(nextMonthFirstDay - oneDay);
      let month = parseInt(lastTime.getMonth() + 1);
      let day = lastTime.getDate();
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      return date.getFullYear() + "-" + month + "-" + day;
    },
    // 获取当月到数第二天
    getCurrentMonthLastDay2() {
      let date = new Date();
      let currentMonth = date.getMonth();
      let nextMonth = ++currentMonth;
      let nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
      let oneDay = 1000 * 60 * 60 * 24;
      let lastTime = new Date(nextMonthFirstDay - oneDay);
      let month = parseInt(lastTime.getMonth() + 1);
      let day = lastTime.getDate();
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      return date.getFullYear() + "-" + month + "-" + (day * 1 - 1);
    },
    // 获取当月到数第3天
    getCurrentMonthLastDay3() {
      let date = new Date();
      let currentMonth = date.getMonth();
      let nextMonth = ++currentMonth;
      let nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
      let oneDay = 1000 * 60 * 60 * 24;
      let lastTime = new Date(nextMonthFirstDay - oneDay);
      let month = parseInt(lastTime.getMonth() + 1);
      let day = lastTime.getDate();
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      return date.getFullYear() + "-" + month + "-" + (day * 1 - 2);
    },
    //获取当月到数第4天
    getCurrentMonthLastDay4() {
      let date = new Date();
      let currentMonth = date.getMonth();
      let nextMonth = ++currentMonth;
      let nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
      let oneDay = 1000 * 60 * 60 * 24;
      let lastTime = new Date(nextMonthFirstDay - oneDay);
      let month = parseInt(lastTime.getMonth() + 1);
      let day = lastTime.getDate();
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      return date.getFullYear() + "-" + month + "-" + (day * 1 - 3);
    },
  },
};
</script>

<style lang="less" scoped>
.theTestReport {
  position: relative;
  &::after {
    content: "[上传附件]";
    display: block;
    position: absolute;
    top: 14px;
    left: 116px;
    font-size: 14px;
    width: max-content;
    height: auto;
    color: gray;
    transform: scale(1);
  }
}

#physics-add {
  width: 100vw;
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;

  /deep/ .van-nav-bar {
    .van-nav-bar__title {
      font-family: "Inter";
      font-style: normal;
      font-weight: 600;
      font-size: 18px;
      line-height: 20px;
      text-align: center;
      letter-spacing: -0.24px;
      color: #333333;
    }

    .van-nav-bar__content {
      .van-nav-bar__left {
        i {
          font-size: 20px;
          color: #999999;
        }
      }
    }
  }

  .contaniner {
    width: 100%;
    height: 0;
    flex: 1;
    overflow-y: auto;

    /deep/ .van-form {
      .form-group {
        box-sizing: border-box;
        padding: 0 12px;
        background: #ffffff;
      }
      .mandatory{
            position: relative;
            &::after{
                content: '*';
                display: block;
                position: absolute;
                left: 5px;
                top: 14px;
                font-size: 16px;
                color: red;
                transform: scale(1);

            }
        }
        .mandatory2{
            position: relative;
            &::after{
                content: '*';
                display: block;
                position: absolute;
                left: 5px;
                top: 20px;
                font-size: 16px;
                color: red;
                transform: scale(1);

            }
        }
      .van-field {
        font-family: "Inter";
        font-style: normal;
        font-weight: 400;
        font-size: 16px;
        line-height: 24px;
        color: #666666;
        padding: 12px 4px;
        padding-left: 15px !important;
        border-bottom: 1px solid #e8e8e8;

        .van-field__label {
          span {
            white-space: nowrap;
          }
        }

        .van-field__value {
          .van-field__body {
            .van-field__control {
              .van-radio-group {
                width: 80%;

                .van-row {
                  width: 100%;

                  .van-radio {
                    margin: 0;

                    .van-radio__icon {
                      height: 16px;
                      width: 16px;

                      .svg-icon {
                        height: 16px;
                        width: 16px;
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }

      .btn-add-detailed {
        font-family: "ABeeZee";
        font-style: normal;
        font-weight: 400;
        font-size: 16px;
        line-height: 20px;
        text-align: center;
        letter-spacing: -0.24px;
        color: #0e86d1;
        border: none;
      }
    }

    .btn-groups {
      width: 100%;
      box-sizing: border-box;
      padding: 18px 12px;

      .btn-submit {
        background: #0e86d1;
        border-radius: 4px;
        font-family: "Inter";
        font-style: normal;
        font-weight: 400;
        font-size: 16px;
        line-height: 19px;
        color: #ffffff;
      }
    }
  }
}
</style>
